from django.conf import settings
from django.core.mail import send_mail
from django.contrib.auth import login, authenticate, logout
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from pymysql import DatabaseError
from courses.models import Course
from operation.models import UserCourse, UserFavorite, UserMessage
from organization.models import CourseOrg, Teacher
from users.forms import RegisterForm, LoginForm, ForgetForm, ModifyPwdForm, UploadImageForm, UserInfoForm
from users.models import UserProfile
from users.utils import generate_verify_email_url, SecretOauth

'''1.首页视图'''
class IndexView(View):
    def get(self, request):
        from users.models import Banner
        all_banners = Banner.objects.all()
        from courses.models import Course
        courses = Course.objects.all()
        banner_courses = Course.objects.all()
        from organization.models import CourseOrg
        course_orgs = CourseOrg.objects.all()
        return render(request, 'index.html', {
            'all_banners': all_banners,
            'courses': courses,
            'banner_courses': banner_courses,
            'course_orgs': course_orgs
        })
'''2.注册页面'''
class RegisterView(View):
    #1、获取用户注册页面
    def get(self, request):
        #生成表单对象
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})
    #2、点击注册保存用户数据
    def post(self, request):
        # 获取表单数据
        data = request.POST
        # 生成表单对象
        register_form = RegisterForm(data)
        # 验证表单
        res = register_form.is_valid()
        # 可以通过error属性获取验证失败的原因
        error = register_form.errors
        if res:
            email = register_form.cleaned_data['email']
            username = email
            password = register_form.cleaned_data['password']
            try:
                user = UserProfile.objects.create_user(username=username, email=email, password=password) #在mysql中创建用户
            except DatabaseError:
                return render(request, 'register.html', {'register_form':register_form})
            login(request, user) #状态保持
            response = redirect(reverse('users:index'))#注册成功时重定向至首页
            response.set_cookie('username', user.username, max_age=3600*24*15) #设置cookie
            return response
        else:
            # 验证失败返回表单对象，在模板中渲染错误原因
            return render(request, 'register.html', {'register_form': register_form})
'''3.登录页面'''
class LoginView(View):
    #1、获取登录页面
    def get(self, request):
        return render(request, 'login.html')
    #2、完成登录请求
    def post(self, request):
        # 获取表单数据
        data = request.POST
        # 生成表单对象
        login_form = LoginForm(data)
        # 验证表单
        res = login_form.is_valid()
        # 可以通过error属性获取验证失败的原因
        error = login_form.errors
        if res:
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            user = authenticate(username=username, password=password)  # 用django自带的认证,验证用户名和密码
            if user is None:
                return render(request, 'login.html', {'login_form': login_form})
            login(request, user)  # 状态保持
            response = redirect(reverse('users:index'))  # 注册成功时重定向至首页
            response.set_cookie('username', user.username, max_age=3600 * 24 * 15)  # 设置cookie
            return response
        else:
            # 验证失败返回表单对象，在模板中渲染错误原因
            return render(request, 'login.html', {'login_form': login_form})
'''4.忘记密码'''
class ForgetPwdView(View):
    #1 、获取忘记密码页面
    def get(self, request):
        forget_form = ForgetForm()
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})
    #2、发送邮件
    def post(self, request):
        data = request.POST
        forget_form = ForgetForm(data)
        res = forget_form.is_valid()
        if res:
            email = forget_form.cleaned_data['email']
            try:
                user = UserProfile.objects.get(email=email)
            except Exception as e:
                return render(request, 'forgetpwd.html', {'forget_form': forget_form})
            verify_url = generate_verify_email_url(email)
            subject = '博学谷邮箱验证'
            html_message = '<p>尊敬的用户您好!</p>' \
                           '<p>感谢您使用博学谷(忘记密码)功能...</p>' \
                           '<p>您的邮箱为:%s 请点击此连接验证您的邮箱:</p>' \
                           '<p> <a href="%s"> %s </a> </p>' % (email, verify_url, verify_url)
            try:
                send_mail(subject, "", settings.EMAIL_FROM, [email], fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=html_message)
            except Exception as e:
                return render(request, 'forgetpwd.html', {'forget_form': forget_form})
            return render(request, 'send_success.html')
        else:
            return render(request, 'forgetpwd.html', {'forget_form': forget_form})
'''5.1重置密码'''
class ResetView(View):
    #1、获取修改密码页面
    def get(self, request):
        token = request.GET.get('token')
        try:
            token_dict = SecretOauth().loads(token)
        except Exception as e:
            return render(request, 'active_fail.html')
        email = token_dict['email']
        try:
            user = UserProfile.objects.get( email=email)
        except Exception as e:
            return render(request, 'active_fail.html')
        return render(request, 'password_reset.html', {'email': email})
    #2、设置新的密码
    def post(self, request):
        data = request.POST
        modifypwd_form = ModifyPwdForm(data)
        res = modifypwd_form.is_valid()
        error = modifypwd_form.errors
        if res:
            new_password1 = modifypwd_form.cleaned_data['password1']
            new_password2 = modifypwd_form.cleaned_data['password2']
            email = data.get('email')
            if new_password1 != new_password2:
                return render(request, 'active_fail.html')
            try:
                user = UserProfile.objects.get(email=email)
                user.set_password(new_password1)
                user.save()
            except Exception as e:
                return render(request, 'password_reset.html', {'email': email})
            return redirect(reverse('users:login'))
'''5.2修改密码'''
class ModifyView(View):
    # 1、获取修改密码页面
    def get(self, request):
        cookies = request.COOKIES.get('username')
        if cookies:
            email = cookies
            return render(request, 'password_reset.html', {'email': email})
        else:
            return redirect(reverse('users:login'))
'''6.1用户中心-->修改个人资料'''
class UserInfoView(View):
    #1 、获取当前登录用户信息
    def get(self, request):
        return render(request, 'usercenter-info.html')
    #3、修改用户信息
    def post(self, request):
        data = request.POST
        userinfo_form = UserInfoForm(data)
        res = userinfo_form.is_valid()
        if res:
            nick_name = userinfo_form.cleaned_data['nick_name']
            gender = userinfo_form.cleaned_data['gender']
            # birthday = userinfo_form.cleaned_data['birthday']
            address = userinfo_form.cleaned_data['address']
            mobile = userinfo_form.cleaned_data['mobile']
            birthday = data.get('birthday')
            try:
                user = UserProfile.objects.get(email=request.user.email)
                user.nick_name = nick_name
                user.gender = gender
                user.birthday = birthday
                user.address = address
                user.mobile = mobile
                user.save()
            except Exception as e:
                return JsonResponse({"status": "error"})
            return JsonResponse({"status":"success"})
        else:
            return JsonResponse({"status": "error"})
'''6.1用户中心-->修改头像'''
class UploadImageView(View):
    def post(self, request):
        data = request.POST
        file = request.FILES
        uploadimage_form = UploadImageForm(data, file)
        res = uploadimage_form.is_valid()
        if res:
            image = uploadimage_form.cleaned_data['image']
            try:
                user = UserProfile.objects.get(email=request.user.email)
                user.image = image
                user.save()
            except Exception as e:
                return JsonResponse({"status": "error"})
            return JsonResponse({"status": "success", "msg": '头像修改成功'})
        else:
            return JsonResponse({"status": "error"})
'''6.2用户中心-->我的课程'''
class MyCourseView(View):
    def get(self, request):
        try:
            #过滤UserCourse中的用户的courses,渲染到前端
            user_courses = UserCourse.objects.filter(user=request.user)
            return render(request, 'usercenter-mycourse.html', {'user_courses': user_courses})
        except Exception as e:
            return render(request, 'usercenter-mycourse.html')
'''6.3用户中心-->我的收藏-->课程学校'''
class MyFavOrgView(View):
    def get(self, request):
        #过滤出用户收藏的课程学校
        data = UserFavorite.objects.filter(fav_type=2, user=request.user.id)
        '''拼接出 org_list数据形式，
        [
            {'org_id':收藏学校的id,'org': 课程学校对像（CourseOrg对象）}，
            {'org_id':收藏学校的id,'org': 课程学校对象（CourseOrg类对象）}，
        ]'''
        org_list = [CourseOrg.objects.get(id=i.fav_id) for i in data]
        return render(request, 'usercenter-fav-org.html', {'org_list': org_list})
'''6.3用户中心-->我的收藏-->授课教师'''
class MyFavTeacherView(View):
    def get(self, request):
        # 过滤出用户收藏的授课教师
        data = UserFavorite.objects.filter(fav_type=3, user=request.user.id, )
        teacher_list = [Teacher.objects.get(id=i.fav_id) for i in data]
        return render(request, 'usercenter-fav-teacher.html', {'teacher_list': teacher_list})
'''6.3用户中心-->我的收藏-->公开课程'''
class MyFavCourseView(View):
    def get(self, request):
        # 过滤出用户收藏的公开课程
        data = UserFavorite.objects.filter(fav_type=1, user=request.user.id, )
        course_id = [Course.objects.get(id=i.fav_id) for i in data]
        return render(request, 'usercenter-fav-course.html', {'course_list': course_id})
'''6.4用户中心-->我的消息'''
class MyMessageView(View):
    def get(self, request):
        #过滤UserMessage的用户的messages
        messages = UserMessage.objects.filter(user=request.user.id)
        #对messages进行分页
        paginator = Paginator(messages, 10)
        page_mun = request.GET.get('page', 1)
        messages = paginator.page(page_mun)
        return render(request, 'usercenter-message.html', {'messages': messages})
'''7.退出登录'''
class LogoutView(View):
    def get(self, request):
        logout(request)  # 退出登录状态
        response = redirect(reverse('users:login'))  # 退出登录,重定向到登录页
        #清理cookie
        response.delete_cookie('username')
        return response